package com.example.feifei.net.download.service;

import android.content.Context;
import android.content.Intent;
import android.util.Log;

import com.example.feifei.net.download.bean.FileInfo;
import com.example.feifei.net.download.bean.ThreadInfo;
import com.example.feifei.net.download.db.ThreadDAOImpl;
import com.example.feifei.utils.LogUtils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.List;

/**
 * 单线程下载任务类
 * Created by Administrator on 2018\6\13 0013.
 */

public class DownloadTask {

    private Context mContext = null;
    private FileInfo fileInfo = null;
    private ThreadDAOImpl mThreadDAO = null;
    private long mFinished = 0;
    public boolean isPause = false;

    public DownloadTask(Context mContext, FileInfo fileInfo) {
        this.mContext = mContext;
        this.fileInfo = fileInfo;
        mThreadDAO = new ThreadDAOImpl(mContext);
    }

    /**
     * 下载线程
     */
    public void download(){
        List<ThreadInfo> threadInfos = mThreadDAO.getThread(fileInfo.getUrl());
        Log.e("threadsize==", threadInfos.size() + "");
        ThreadInfo info;
        if(threadInfos.size() == 0){
            info = new ThreadInfo(0,fileInfo.getUrl(),0,fileInfo.getLength(),0);
        }else{
            info = threadInfos.get(0);
        }
        new DownloadThread(info).start();
    }

    /**
     * 下载线程
     */
    class DownloadThread extends Thread{
        private ThreadInfo threadInfo;

        public DownloadThread(ThreadInfo threadInfo) {
            this.threadInfo = threadInfo;
        }

        @Override
        public void run() {
           //向数据库插入线程信息
            Log.e("isExists==", mThreadDAO.isExists(threadInfo.getUrl(), threadInfo.getId()) + "");
            if(!mThreadDAO.isExists(threadInfo.getUrl(),threadInfo.getId())){
                mThreadDAO.insertThread(threadInfo);
            }
            HttpURLConnection connection = null;
            RandomAccessFile raf;
            InputStream is;
            try {
                URL url = new URL(threadInfo.getUrl());
                connection = (HttpURLConnection) url.openConnection();
                connection.setConnectTimeout(3000);
                connection.setRequestMethod("GET");
                connection.setRequestProperty("Accept-Encoding", "identity");
                long start = threadInfo.getStart()+threadInfo.getFinish();
                connection.setRequestProperty("Range","bytes="+start+"-"+threadInfo.getEnd());
                File file = new File(DownloadService.DOWNLOAD_PATH,fileInfo.getFileName());
                raf = new RandomAccessFile(file,"rwd");
                raf.seek(start);

                Intent intetn = new Intent(DownloadService.ACTION_UPDATE);
                mFinished+=threadInfo.getFinish();
                Log.e("threadInfo.getFinish==", threadInfo.getFinish() + "");
                Log.e("getResponseCode ===", connection.getResponseCode() + "");
                //开始下载
                if(connection.getResponseCode() == HttpURLConnection.HTTP_PARTIAL){
                    Log.e("getContentLength==", connection.getContentLength() + "");
                    is = connection.getInputStream();
                    byte[] buffer = new byte[1024*4];
                    int len = -1;
                    long time = System.currentTimeMillis();
                    while ((len = is.read(buffer))!= -1){
                        //下载暂停，保存进度
                        if(isPause){
                            Log.e("mfinished==", mFinished + "");
                            mThreadDAO.updateThread(fileInfo.getUrl(),fileInfo.getId(),mFinished);
                            return;
                        }
                        //写入文件
                        raf.write(buffer,0,len);
                        //把下载进度发送给Activity
                        mFinished+=len;
                        if(System.currentTimeMillis()- time >1000){
                            time = System.currentTimeMillis();
                           intetn.putExtra("finished",(int)(mFinished *100/fileInfo.getLength()));
                           mContext.sendBroadcast(intetn);
                        }
                    }
                    LogUtils.e("下载最终的进度===="+mFinished+"     获取的网络文件长度=="+fileInfo.getLength());
                    intetn.putExtra("finished",100);
                    mContext.sendBroadcast(intetn);
                    mThreadDAO.deleteThread(fileInfo.getUrl(),fileInfo.getId());
                    is.close();

                }
                raf.close();

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (ProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
